/* Orbas:
 *     A open source CORBA Specification implementation from Huihoo.
 *
 * Copyright 2002-2003 Huihoo.org, Inc. All Right Reserved.
 *
 * This software is licensed under LGPL license.
 * See terms of license at gnu.org.
 *
 * For more information, visit:
 *
 * http://www.huihoo.org/orbas
 */


package org.huihoo.orbas.orb.thread;

/**
 * <p>Description: </p>
 * A queue for incoming request.
 * <p>Copyright (c) 2002,2003</p>
 * <p>Company: <a href="http://www.huihoo.org/">huihoo.org</a></p>
 * @author <a href="http://www.huihoo.org/~mep">mep(mep@huihoo.com)</a>
 * @see <a href="http://www.huihoo.org/orbas">http://www.huihoo.org/orbas</a>
 * @version 1.0
 */


import com.cognition.util.j2me.Logger;
import com.cognition.util.j2me.SystemLogger;
import org.huihoo.orbas.orb.ORB;
import org.huihoo.orbas.orb.protocols.Transport;


public class RequestQueue {
    public static final String LOG_TAG = "RequestQueue";
    private static Logger logger = SystemLogger.getLogger(SystemLogger.LOGGER_CONSOLE);
    java.util.Vector queue;
    ORB orb;
    private String name;

    /**
     * Creates a synchronized request queue.
     * @param orb the parent orb
     * @param n the name of the request queue.
     */
    public RequestQueue(ORB orb, String n) {
        this.orb = orb;
        queue = new java.util.Vector();
        name = n;
    }

    public synchronized void add2Queue(Transport t) {
        queue.insertElementAt(t, 0);
        try {
            notifyAll();
        }
        catch(java.lang.IllegalMonitorStateException e) {
            System.out.println("Request Queue Error.");
        }
    }

    public synchronized Transport removeFromQueue() {

        Transport t = null;
        while(true) {
            try {
                t = (Transport)queue.elementAt(queue.size()-1);
                queue.removeElement(t);
                logger.debug(LOG_TAG, name + " retrieved an element from the queue.");
                return t;
            }
            catch(java.lang.ArrayIndexOutOfBoundsException e) {
                try {
                    logger.debug(LOG_TAG, name + " waiting");
                    wait();
                }
                catch(java.lang.InterruptedException ex) {
                    continue;
                }
            }
        }
    }
}